package com.powernode.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.powernode.constant.ManagerConstants;

import com.powernode.domain.SysRole;
import com.powernode.domain.SysRoleMenu;

import com.powernode.dto.SysRoleAddOrUpdateParam;
import com.powernode.mapper.SysRoleMapper;
import com.powernode.mapper.SysRoleMenuMapper;
import com.powernode.service.SysRoleMenuService;
import com.powernode.service.SysRoleService;
import com.powernode.utils.AuthUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import javax.annotation.Resource;

@Service
@CacheConfig(cacheNames = "com.powernode.service.impl.SysRoleServiceImpl")
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Resource
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Resource
    private SysRoleMenuService sysRoleMenuService;

    @Override
    @Cacheable(key = ManagerConstants.SYS_ALL_ROLE_KEY)
    public List<SysRole> queryAllSysRoleList() {
        return sysRoleMapper.selectList(new LambdaQueryWrapper<SysRole>()
                .orderByDesc(SysRole::getCreateTime));
    }

    // 新增角色
    @Override
    @CacheEvict(key = ManagerConstants.SYS_ALL_ROLE_KEY)
    @Transactional(rollbackFor = Exception.class)
    public Integer addSysRole(SysRoleAddOrUpdateParam addOrUpdateParam) {
        Long createUserId = AuthUtils.getLoginUserId();
        addOrUpdateParam.setCreateTime(new Date());
        addOrUpdateParam.setCreateUserId(createUserId);
        int count = sysRoleMapper.insert(addOrUpdateParam);
        if (count > 0) {
            Long roleId = addOrUpdateParam.getRoleId();
            List<Long> menuIdList = addOrUpdateParam.getMenuIdList();
            if (!CollectionUtils.isEmpty(menuIdList)) {
                List<SysRoleMenu> roleMenuList = menuIdList.stream()
                        .map(menuId -> {
                            SysRoleMenu roleMenu = new SysRoleMenu();
                            roleMenu.setRoleId(roleId);
                            roleMenu.setMenuId(menuId);
                            return roleMenu;
                        })
                        .collect(Collectors.toList());
                sysRoleMenuService.saveBatch(roleMenuList);
            }
        }
        return count;
    }

    // 查询角色详情
    @Override
    public SysRole querySysRoleDetailById(Long roleId) {
        SysRole sysRole = sysRoleMapper.selectById(roleId);
        List<SysRoleMenu> sysRoleMenuList = sysRoleMenuMapper.selectList(new LambdaQueryWrapper<SysRoleMenu>()
                .eq(SysRoleMenu::getRoleId, roleId)
        );
        if (CollectionUtil.isNotEmpty(sysRoleMenuList)) {
            List<Long> menuIdList = sysRoleMenuList.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
            sysRole.setMenuIdList(menuIdList);

        }
        return sysRole;
    }

    /**
     * 修改角色
     *
     * @param sysRole
     * @return
     */
    @Override
    @CacheEvict(key = ManagerConstants.SYS_ALL_ROLE_KEY)
    @Transactional(rollbackFor = Exception.class)
    public Boolean modifySysRole(SysRole sysRole) {
        // 获取角色id
        Long roleId = sysRole.getRoleId();
        // 删除角色原有的权限id
        sysRoleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>()
                .eq(SysRoleMenu::getRoleId, roleId)
        );

        // 获取角色新的权限id集合
        List<Long> menuIdList = sysRole.getMenuIdList();
        // 创建角色与权限关系对象集合
        List<SysRoleMenu> roleMenuList = new ArrayList<>();
        // 判断权限id集合是否有值
        if (CollectionUtil.isNotEmpty(menuIdList) && menuIdList.size() != 0) {
            // 循环遍历权限id集合
            menuIdList.forEach(menuId -> {
                // 创建角色与权限关系对象
                SysRoleMenu roleMenu = new SysRoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(menuId);
                // 将角色与权限关系记录添加到集合中
                roleMenuList.add(roleMenu);
            });
            // 批量添加角色与权限关系记录
            sysRoleMenuService.saveBatch(roleMenuList);
        }
        // 修改角色信息
        return sysRoleMapper.updateById(sysRole) > 0;
    }


    /**
     * 批量/单个删除角色
     *
     * @param roleIdList 角色ID列表，用于批量删除角色
     * @return 删除操作是否成功
     */
    @Override
    @CacheEvict(key = ManagerConstants.SYS_ALL_ROLE_KEY)
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeSysRoleListByIds(List<Long> roleIdList) {
        // 删除角色原有的权限
        sysRoleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>()
                .in(SysRoleMenu::getRoleId, roleIdList)
        );
        // 批量删除角色
        return sysRoleMapper.deleteBatchIds(roleIdList) == roleIdList.size();
    }

}

